package org.wzl.todolisthelper.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.wzl.todolisthelper.convert.UserConvert;
import org.wzl.todolisthelper.domain.User;
import org.wzl.todolisthelper.dto.JsCode2SessionResult;
import org.wzl.todolisthelper.mapper.UserMapper;
import org.wzl.todolisthelper.service.ProfileService;
import org.wzl.todolisthelper.service.UploadService;
import org.wzl.todolisthelper.utils.IdCommonGen;
import org.wzl.todolisthelper.utils.UserUtil;
import org.wzl.todolisthelper.vo.UserUpdateDTO;
import org.wzl.todolisthelper.vo.UserVO;

import java.util.List;

@Slf4j
@Service
public class ProfileServiceImpl implements ProfileService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserConvert userConvert;

    @Resource
    private UploadService uploadService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User addUserIfNotExists(JsCode2SessionResult jsCode2SessionResult) {
        List<User> users = userMapper.selectList(Wrappers.<User>lambdaQuery()
                .eq(User::getWxId, jsCode2SessionResult.getOpenId()));

        if (CollectionUtils.isEmpty(users)) {
            String id = IdCommonGen.generateId();
            User user = User.builder()
                    .id(id)
                    .wxId(jsCode2SessionResult.getOpenId())
                    .nickname("用户" + id.substring(0, 5))
                    .build();
            userMapper.insert(user);
            return user;
        }
        return users.get(0);
    }

    @Override
    public UserVO getById(String id) {
        return userConvert.toVO(userMapper.selectById(id));
    }

    @Override
    public UserVO getUserInfo() {
        return userConvert.toVO(userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getId, UserUtil.getCurrentUserId())));
    }

    @Override
    public void uploadAvatar(String base64Img) {
        log.info("file:{}", base64Img);
        String currentUserId = UserUtil.getCurrentUserId();
        String imgUrl = uploadService.uploadBase64Img(base64Img, currentUserId);
        userMapper.updateById(User.builder()
                .id(currentUserId)
                .avatar(imgUrl)
                .build());
    }

    @Override
    public void update(UserUpdateDTO userUpdateDTO) {
        String currentUserId = UserUtil.getCurrentUserId();
        userMapper.updateById(User.builder()
                .id(currentUserId)
                .nickname(userUpdateDTO.getNickname())
                .build());
    }


}
